package com.itheima.mobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
/**
 * 快速登陆控制层
 *
 * @author ：zengjie
 * @date ：2020/11/14
 */
@RestController
@RequestMapping("/login")
public class MbileLoginController {
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memeberService;

    /**
     * 快速登陆
     * {"telephone":"15112341234","validateCode":"123"}
     *
     * @return
     */
    @RequestMapping(value = "/check", method = RequestMethod.POST)
    public Result login(HttpServletResponse response, @RequestBody Map map) {

        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");

        String redisCode = jedisPool.getResource().get(RedisMessageConstant.SENDTYPE_LOGIN + "_" + telephone);

        if (StringUtils.isEmpty(validateCode) || StringUtils.isEmpty(redisCode) || !validateCode.equals(redisCode)) {
            return new Result(false, MessageConstant.LOGIN_FAIL);
        }

        Member member = memeberService.findByTelephone(telephone);
        //如果不存在就自动注册
        if (member == null) {
            member = new Member();
            member.setPhoneNumber(telephone);//手机号码
            memeberService.add(member);
        }
        //进行登录,并将注册手机号存入Cookie返回客户端
        Cookie cookie = new Cookie("login_member_telephone",telephone);
        //所有页面可以使用
        cookie.setPath("/");
        //生命周期一个月
        cookie.setMaxAge(60*60*24*30);
        response.addCookie(cookie);
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }

}
